<template>
  <div class="add-friend-auto">
    <!-- 上传text文件 -->
    <div class="uplode-number">
      <span class="tip">选择号码</span>
      <input class="tip" type="file" accept="text/plain" @change="openFile($event)" />
      <span class="tip">{{phones.length}}个号码</span>
      <el-radio v-model="autoDistribution" label="auto">自动分配</el-radio>
      <el-radio v-model="autoDistribution" label="manual">手动分配</el-radio>
    </div>
    <!-- 微信列表 & 设置参数 -->
    <div class="add-friend-auto-config">
      <el-table :data="wechatsLogin" height="100%" border>
        <el-table-column fixed prop="WeChatNo" label="微信号"></el-table-column>
        <el-table-column fixed prop="WeChatNick" label="微信昵称"></el-table-column>
        <el-table-column fixed prop="Avatar" label="头像" width="60">
          <template slot-scope="scope">
            <el-avatar :size="40" :src="scope.row.Avatar" @error="return true">
              <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="Province" label="省份"></el-table-column>
        <el-table-column prop="City" label="市区"></el-table-column>
        <el-table-column label="添加数量">
          <template slot-scope="scope">
            <!-- :max="getMaxNumber(scope.row.WeChatId)" -->
            <el-input-number
              size="small"
              :min="0"
              v-model="numberMap[scope.row.WeChatId]"
              :step="1"
              step-strictly
              :disabled="autoDistribution === 'auto'"
            ></el-input-number>
            <!-- @change="handleChange($event,scope.row.WeChatId)" -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 创建任务 -->
    <div class="add-friend-auto-oprations">
      <div class="break-time">
        <span class="tip">添加限制</span>
        <el-input-number
          size="small"
          v-model="limitNumber"
          controls-position="right"
          :min="1"
          :max="100"
          style="margin:0 5px"
        ></el-input-number>
      </div>
      <div class="break-time">
        <span class="tip">时间间隔（分）</span>
        <el-input-number
          size="small"
          v-model="breakTime"
          controls-position="right"
          :min="1"
          :max="59"
          style="margin:0 5px"
        ></el-input-number>
      </div>
      <div class="start-time">
        <span class="tip">起始时间</span>
        <el-date-picker
          v-model="startTime"
          type="datetime"
          placeholder="选择日期时间"
          clearable
          size="small"
        ></el-date-picker>
      </div>
      <el-button
        size="small"
        type="primary"
        @click="sureSend"
        :disabled="sending"
        :loading="sending"
      >创建任务</el-button>
      <el-button size="small" type="info" @click="showTaskDialog">任务日志</el-button>
    </div>

    <!-- 任务日志 -->
    <el-dialog class="add-friend-auto-dialog" title="批量加好友日志" :visible.sync="taskLogVisiable">
      <el-table :data="logs[currentPage-1]" stripe>
        <el-table-column type="index" label="序号" width="60px"></el-table-column>
        <el-table-column label="微信昵称" width="170px">
          <template slot-scope="scope">
            <span
              v-if="scope.row.wechatid && wechatsMap[scope.row.wechatid]"
              v-text="wechatsMap[scope.row.wechatid].WeChatNick"
            ></span>
            <span v-else>{{scope.row.wechatid}}</span>
          </template>
        </el-table-column>
        <el-table-column label="执行次数">
          <template slot-scope="scope">{{scope.row.doingsize}}</template>
        </el-table-column>
        <el-table-column label="成功次数">
          <template slot-scope="scope">
            <span style="color:#67c23a;" v-text="scope.row.successsize || ''"></span>
          </template>
        </el-table-column>
        <el-table-column label="失败次数">
          <template slot-scope="scope">
            <span
              v-if="scope.row.doingsize && scope.row.successsize"
              style="color:red;"
              v-text="scope.row.doingsize - scope.row.successsize"
            ></span>
          </template>
        </el-table-column>
        <el-table-column label="总次数">
          <template slot-scope="scope">{{scope.row.totalsize}}</template>
        </el-table-column>
        <el-table-column label="任务结果">
          <template slot-scope="scope">
            <span v-text="scope.row.state === 0 ? '已结束':'进行中' "></span>
          </template>
        </el-table-column>
        <el-table-column prop="execute_time" label="下次执行时间" width="150px"></el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[15, 30, 45, 60]"
        :page-size="pageSize"
        :pager-count="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="autoAddFriendLog.length"
      ></el-pagination>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";

export default {
  name: "ToolsAddFriendAuto",
  data() {
    return {
      phones: [],
      autoDistribution: 'auto', // 自动分配
      startTime: new Date().getTime(), // 添加的起始时间
      limitNumber: 15, // 添加上限
      breakTime: 1, // 添加的间隔时间
      numberMap: {}, // 每个微信的添加数量
      taskLogVisiable: false, // 显示日志
      sending: false, // 显示日志
      pageSize: 15, // 每页几个数据
      currentPage: 1, // 当前页
    };
  },
  computed: {
    ...mapGetters({
      wechats: "conversation/wechats",
      wechatsLogin: "conversation/wechatsLogin",
      autoAddFriendLog: "nedb/autoAddFriendLog",
    }),
    wechatsMap() {
      let wm = {}
      this.wechats.forEach((e) => {
        wm[e.WeChatId] = e
      })
      return wm
    },
    logs() {
      let logsArry = []
      let size = this.pageSize
      for (let i = 0; i < this.autoAddFriendLog.length; i += size) {
        logsArry.push(this.autoAddFriendLog.slice(i, i + size))
      }
      return logsArry
    },
    // 测试数据
    testWechats() {
      let wechats = []
      for (let index = 0; index < 10; index++) {
        // const element = array[index];
        wechats = wechats.concat(this.wechatsLogin)
      }
      return wechats
    }
  },
  watch: {
    autoDistribution(val) {
      if (val === 'auto') {
        this.autoDispatch()
      }
    }
  },
  methods: {
    // 修改pageSize
    handleSizeChange(val) {
      if (this.pageSize === val) return
      this.pageSize = val
    },
    // 修改当前页
    handleCurrentChange(val) {
      this.currentPage = val
    },
    // 解析txt
    openFile(event) {
      let file = event.target.files[0];
      let reader = new FileReader();
      if (file) {
        reader.readAsText(file);
        reader.onload = (evt) => {
          //读取完文件之后会回来这里
          var fileString = evt.target.result; // 读取文件内容
          this.phones = fileString.split("\r\n");
          // 自动分配手机号
          if (this.phones.length > 0 && this.autoDistribution === 'auto') {
            this.autoDispatch()
          }
        }
      } else {
        this.phones = []
      }
    },
    // 自动分配号码
    autoDispatch() {
      let eachP = this.phones.length / this.wechatsLogin.length
      this.wechatsLogin.forEach((e, index) => {
        if (index === this.wechatsLogin.length - 1) {
          this.$set(this.numberMap, e.WeChatId, Math.floor(eachP))
        } else {
          this.$set(this.numberMap, e.WeChatId, Math.round(eachP))
        }
      })
    },
    // 添加数量的最大值
    getMaxNumber(wxid) {
      let tn = 0
      for (const key in this.numberMap) {
        if (this.numberMap.hasOwnProperty(key) && key !== wxid) {
          const element = this.numberMap[key]
          tn += element
        }
      }
      let maxP = this.phones.length - tn
      return maxP > 0 ? maxP : 0
    },
    // 时间戳转换成 2020-09-21 16:44
    transformTime(times) {
      var date = new Date(times)
      let Y = date.getFullYear() + '-'
      let M =
        (date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1) + '-'
      let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      let m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      // let s = date.getSeconds()
      let time = Y + M + D + h + m
      return time
    },
    // 提交表单
    sureSend() {
      let config = []
      for (const key in this.numberMap) {
        if (this.numberMap.hasOwnProperty(key)) {
          config.push({
            wechatid: key,
            add_count: this.numberMap[key]
          })
        }
      }
      let content = {
        accountid: this.$store.getters.currentUser.UnionId,
        execute_time: this.transformTime(this.startTime), // 执行时间
        between_time: this.breakTime, // 间隔时间
        phones: this.phones, // 电话号码集合
        config: config, // 每个微信号加的数量
        sayhellosize: this.limitNumber, // 打招呼次数
        message: '' // 描述 非必传
      }
      console.log(content)
      this.$store.dispatch("websocket/AutoFriendAddTask", content)
      this.sending = true
      setTimeout(() => {
        this.sending = false
      }, 1000);

    },
    // 获取并显示批量加好友任务列表
    showTaskDialog() {
      this.$store.dispatch("websocket/GetAutoFriendAddTaskList")
      this.taskLogVisiable = !this.taskLogVisiable
    },
  },
  created() {
    this.wechatsLogin.forEach(e => {
      this.$set(this.numberMap, e.WeChatId, 0)
    })
  }
};
</script>

<style lang="scss" scoped>
.add-friend-auto {
  height: 100%;
  color: $font-color-1;
  display: flex;
  flex-direction: column;
  .uplode-number {
    padding: 5px;
    font-size: 16px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    .tip {
      margin: 0 5px;
    }
    ::v-deep .el-radio {
      font-size: 16px;
      margin-left: 10px;
      .el-radio__label {
        font-size: 16px;
      }
    }
  }

  .add-friend-auto-config {
    padding: 5px;
    flex: auto;
    display: flex;
    flex-direction: column;
    border-bottom: $border-color-1 solid 2px;
    overflow: hidden;
  }

  .add-friend-auto-oprations {
    width: 100%;
    padding: 5px;
    display: flex;
    .break-time,
    .start-time {
      padding: 0 25px 0 0;
      .tip {
        margin-right: 10px;
        font-size: 16px;
      }
    }
  }

  ::v-deep .add-friend-auto-dialog {
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .el-dialog {
      height: 60%;
      width: 60%;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      .el-dialog__body {
        flex: 1 1 auto;
        padding: 5px;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        .el-table {
          flex: 1 1 auto;
          overflow: hidden;
          display: flex;
          flex-direction: column;
          .el-table__header-wrapper {
            height: 40px;
            min-height: 40px;
            display: flex;
            align-items: center;
          }
          .el-table__body-wrapper {
            flex: 1 1 auto;
            overflow-y: auto;
          }
        }
        .el-pagination {
          padding: 5px;
          display: flex;
          justify-content: center;
          align-items: center;
          border-top: solid 1px $border-color-1;
          background-color: white;
        }
      }
    }
  }
}
</style>
